# -*- coding: utf-8 -*-
from django.db import models
from django import forms
from django.forms.util import ValidationError

class MMIntegerField(models.IntegerField):
  """
  Min Max Integer Field - use in place of models.IntegerField
  """
  def __init__(self, verbose_name=None, min_value=None, max_value=None, **kwargs):
    self.min_value = min_value
    self.max_value = max_value
    models.IntegerField.__init__(self, verbose_name, **kwargs)
    
  def formfield(self, **kwargs):
    return models.IntegerField.formfield(self, min_value = self.min_value, max_value = self.max_value, **kwargs)
    
  def get_internal_type(self):
    return "IntegerField"

class EMSOField(forms.CharField):
  """
  A field for entering EMSOs.
  """
  def clean(self, value):
    """
    Validates the input.
    """
    value = super(EMSOField, self).clean(value)
    
    try:
      # special case: foreign student
      if sum([x=='0' for x in value[7:]]) == 6:
        return value
      
      factors = [7, 6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
      number_sum = sum([int(x)*factors[i] for i, x in enumerate(value[:12])])
      
      # Compute remainder and control number
      r = number_sum % 11
      control = 11 - r if r > 0 else 0
      
      if control != int(value[12]):
        raise ValueError
    except (ValueError, IndexError):
      raise ValidationError(u"Vnešeni EMŠO ni veljaven!")
    
    return value

class LecturersField(forms.ModelMultipleChoiceField):
  def label_from_instance(self, obj):
    return str(obj.get_profile())

